package net.stancristian.restnews;

import java.util.ArrayList;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

public class UpdatesService extends IntentService {

	public static final String NOTIFICATION = "net.stancristian.restnews";

	public UpdatesService() {
		super("UpdateRESTNewsService");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			Toast.makeText(this, "Requesting updates...", Toast.LENGTH_SHORT)
					.show();
			String baseApiAddress = getString(R.string.api_base_address);
			String Url = baseApiAddress + "/Updates";
			HttpResponse response = RestNewsClient.getRequestWebService(Url);
			if (response != null
					&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				try {
					JSONObject updates = RestNewsClient
							.GetJsonObjectFromResponse(response);
					if (updates.getInt("NumberOfUpdates") > 0) {
						Intent newIntent = new Intent(NOTIFICATION);
						sendBroadcast(newIntent);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
				Toast.makeText(this, "No updates!", Toast.LENGTH_SHORT).show();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
